package com.sj.parksdk.utils.bdlocation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import android.content.Context;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.baidu.location.BDLocation;
import com.sj.parksdk.ParkSdk;


public class LocationUtils {
    private static final double PI = 3.14159265;

    /**
     * 通过经纬度获取地址信息的另一种方法
     *
     * @param latitude
     * @param longitude
     * @return 城市名
     */
    public static String GetAddr(String latitude, String longitude) {
        String addr = "";
        /*
         * 也可以是http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s，
         * 不过解析出来的是英文地址 密钥可以随便写一个key=abc
         * output=csv,也可以是xml或json，不过使用csv返回的数据最简洁方便解析
         */
        String url = String.format(
                "http://ditu.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s",
                latitude, longitude);
        URL myURL = null;
        URLConnection httpsConn = null;
        try {

            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }

        try {

            httpsConn = (URLConnection) myURL.openConnection();

            if (httpsConn != null) {
                InputStreamReader insr = new InputStreamReader(
                        httpsConn.getInputStream(), "UTF-8");
                BufferedReader br = new BufferedReader(insr);
                String data = null;
                if ((data = br.readLine()) != null) {
                    String[] retList = data.split(",");
                    if (retList.length > 2 && ("200".equals(retList[0]))) {
                        addr = retList[2];
                    } else {
                        addr = "";
                    }
                }
                insr.close();
            }
        } catch (IOException e) {

            e.printStackTrace();
            return null;
        }
        return addr;
    }

    private static double Rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 屏幕两点距离
     *
     * @param screenX1
     * @param screenY1
     * @param screenX2
     * @param screenY2
     * @return
     */
    public static double distanceScreen(double screenX1, double screenY1,
                                        double screenX2, double screenY2) {
        return Math.sqrt(Math.abs(screenX1 - screenX2)
                * Math.abs(screenX1 - screenX2) + Math.abs(screenY1 - screenY2)
                * Math.abs(screenY1 - screenY2));
    }

    /**
     * 判断是否打开GPS
     *
     * @return
     */
    public static boolean isEnabledGPS() {
        return isEnabledProvider(LocationManager.GPS_PROVIDER);
    }

    /**
     * 判断是否连接网络
     *
     * @return
     */
    public static boolean isEnabledNetwork() {
        ConnectivityManager cwjManager = (ConnectivityManager) ParkSdk
                .getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cwjManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断获取定位的设备是否打开
     *
     * @param provider
     * @return
     */
    public static boolean isEnabledProvider(String provider) {
        LocationManager lm = (LocationManager) ParkSdk.getContext()
                .getSystemService(Context.LOCATION_SERVICE);
        return lm.isProviderEnabled(provider);
    }

    public static double[] getAround(Double lat, double lon, int raidus) {
        Double latitude = lat;
        Double longitude = lon;


        Double degree = (24901 * 1609) / 360.0;
        double raidusMile = raidus;

        Double dpmLat = 1 / degree;
        Double radiusLat = dpmLat * raidusMile;
        Double minLat = latitude - radiusLat;
        Double maxLat = latitude + radiusLat;

        Double mpdLng = degree * Math.cos(latitude * (PI / 180));
        Double dpmLng = 1 / mpdLng;
        Double radiusLng = dpmLng * raidusMile;
        Double minLng = longitude - radiusLng;
        Double maxLng = longitude + radiusLng;
        return new double[]{minLat, minLng, maxLat, maxLng};
    }

    @SuppressWarnings("static-access")
    public static boolean isGPSEnabled(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
        List<String> accessibleProviders = locationManager.getProviders(true);
        return accessibleProviders != null && accessibleProviders.size() > 0;
    }

    /**
     * 判断百度定位信息是否有效/中国境内
     *
     * @param location
     * @return
     */
    public static boolean isValidBDLocation(BDLocation location) {
        boolean isValid = false;
        if (location == null) return isValid;
        if (location.getLongitude() != 4.9E-324
                && location.getLatitude() != 4.9E-324
                && location.getLongitude() > 116.0 && location.getLongitude() < 122.0
                && location.getLatitude() > 30.0 && location.getLatitude() < 36.0) {
            isValid = true;
        }
        return isValid;
//        if (location != null && location.getLongitude() != 4.9E-324) {
//            return true;
//        }
    }

    //江苏境内的
    public static boolean isValidLocation(Double longitude, Double latitude) {
        boolean isValid = false;
        if (longitude != null
                && latitude != null
                && longitude != 4.9E-324
                && latitude != 4.9E-324
                //江苏境内
//                && longitude > 116.0 && longitude < 122.0
//                && latitude > 30.0 && latitude < 36.0) {
                //中国境内
                && longitude > 73.80 && longitude < 135.17
                && latitude > 18.0 && latitude < 53.5) {
            isValid = true;
        }
        return isValid;
    }

}
